<template>
  <div class="recycle-view animate-fade-in">
    <!-- 操作栏 -->
    <div class="operation-bar animate-fade-in" style="animation-delay: 0.1s">
      <el-button
        class="dynamic-button restore-button btn-hover"
        type="primary"
        :disabled="!selectedFiles.length"
        @click="handleBatchRestore"
      >
        <el-icon class="btn-icon"><RefreshLeft /></el-icon>
        还原{{ selectedFiles.length ? `(${selectedFiles.length}个文件)` : "" }}
      </el-button>

      <!-- 删除按钮 -->
      <el-button
        class="dynamic-button delete-button btn-hover"
        type="danger"
        :disabled="!selectedFiles.length"
        @click="handleBatchDelete"
      >
        <el-icon class="btn-icon"><Delete /></el-icon>
        彻底删除{{
          selectedFiles.length ? `(${selectedFiles.length}个文件)` : ""
        }}
      </el-button>
    </div>

    <!-- 文件表格 -->
    <FileTable 
      :fileList="fileList" 
      @selection-change="handleSelectionChange"
      :row-class-name="tableRowClassName"
    >
      <template #operation="{ row }">
        <el-button-group>
          <el-tooltip effect="dark" content="还原" placement="top">
            <el-button 
              type="primary" 
              link 
              @click="handleRestore(row)"
              class="btn-icon-hover"
            >
              <el-icon><RefreshLeft /></el-icon>
            </el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="彻底删除" placement="top">
            <el-button 
              type="danger" 
              link 
              @click="handleDelete(row)"
              class="btn-icon-hover"
            >
              <el-icon><Delete /></el-icon>
            </el-button>
          </el-tooltip>
        </el-button-group>
      </template>
    </FileTable>

    <!-- 空状态提示 -->
    <div v-if="fileList.length === 0" class="empty-state animate-fade-in-up">
      <el-icon class="empty-icon"><Delete /></el-icon>
      <p class="empty-text">回收站是空的</p>
      <p class="empty-desc">删除的文件将暂时保存在这里，可随时还原或彻底删除</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Delete, RefreshLeft } from "@element-plus/icons-vue";
import { listRecycleFiles, batchRestore, batchDelete } from "@/api/recycle";
import FileTable from "@/components/file/FileTable.vue";
import { useStorageStore } from "@/store/storage";

const fileList = ref<API.FileDTO[]>([]);
const selectedFiles = ref<API.FileDTO[]>([]);
const storageStore = useStorageStore();
const rowIndex = ref(0); // 用于控制行动画延迟

// 表格行类名，添加动画延迟
const tableRowClassName = ({ rowIndex }: { rowIndex: number }) => {
  return `row-animate-${rowIndex}`;
};

// 获取回收站文件列表
const fetchRecycleFiles = async () => {
  try {
    const response = await listRecycleFiles();
    if (response.data?.success) {
      fileList.value = (response.data?.data ?? []).map((file: API.FileDTO) => ({
        ...file,
        fileType: file.isDir === 1 ? "folder" : file.fileType || "other",
        fileSuffix: file.isDir === 1 ? "folder" : file.fileSuffix || "other",
      }));
      // 重置行索引，确保重新加载时动画正常
      rowIndex.value = 0;
    } else {
      ElMessage.error(response.data?.msg || "获取回收站文件列表失败");
    }
  } catch (error) {
    console.error("获取回收站文件列表失败:", error);
    ElMessage.error("获取回收站文件列表失败");
  }
};

// 处理文件选择
const handleSelectionChange = (selection: API.FileDTO[]) => {
  selectedFiles.value = selection;
};

// 还原单个文件
const handleRestore = async (file: API.FileDTO) => {
  try {
    const response = await batchRestore({
      fileIds: [String(file.id)],
    });

    if (response.data?.success) {
      ElMessage.success("文件还原成功");
      fetchRecycleFiles();
      storageStore.updateStorageInfo();
    } else {
      ElMessage.error(response.data?.msg || "文件还原失败");
    }
  } catch (error) {
    console.error("文件还原失败:", error);
    ElMessage.error("文件还原失败");
  }
};

// 批量还原文件
const handleBatchRestore = async () => {
  if (!selectedFiles.value.length) return;

  try {
    const response = await batchRestore({
      fileIds: selectedFiles.value.map((file) => String(file.id)),
    });

    if (response.data?.success) {
      ElMessage.success("文件还原成功");
      fetchRecycleFiles();
      selectedFiles.value = [];
      storageStore.updateStorageInfo();
    } else {
      ElMessage.error(response.data?.msg || "文件还原失败");
    }
  } catch (error) {
    console.error("文件还原失败:", error);
    ElMessage.error("文件还原失败");
  }
};

// 彻底删除单个文件
const handleDelete = async (file: API.FileDTO) => {
  try {
    await ElMessageBox.confirm("此操作将永久删除该文件, 是否继续?", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    const response = await batchDelete({
      fileIds: [String(file.id)],
    });

    if (response.data?.success) {
      ElMessage.success("文件删除成功");
      fetchRecycleFiles();
    } else {
      ElMessage.error(response.data?.msg || "文件删除失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("文件删除失败:", error);
      ElMessage.error("文件删除失败");
    }
  }
};

// 批量彻底删除文件
const handleBatchDelete = async () => {
  if (!selectedFiles.value.length) return;

  try {
    await ElMessageBox.confirm(
      "此操作将永久删除选中的文件, 是否继续?",
      "警告",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    const response = await batchDelete({
      fileIds: selectedFiles.value.map((file) => String(file.id)),
    });

    if (response.data?.success) {
      ElMessage.success("文件删除成功");
      fetchRecycleFiles();
      selectedFiles.value = [];
    } else {
      ElMessage.error(response.data?.msg || "文件删除失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("文件删除失败:", error);
      ElMessage.error("文件删除失败");
    }
  }
};

onMounted(() => {
  fetchRecycleFiles();
  // 动态添加行动画样式（按索引延迟）
  const style = document.createElement("style");
  let animationStyles = "";
  for (let i = 0; i < 20; i++) { // 预生成20行动画
    animationStyles += `.row-animate-${i} { animation: fadeInUp 0.4s ease forwards; animation-delay: ${i * 0.05}s; opacity: 0; }`;
  }
  style.innerHTML = animationStyles;
  document.head.appendChild(style);
});
</script>

<style scoped>
/* 基础布局 */
.recycle-view { padding: 20px; background: #f8fafc; min-height: calc(100vh - 64px); }
.operation-bar { padding: 0 20px; margin-bottom: 20px; display: flex; gap: 12px; }

/* 按钮样式 */
.dynamic-button { position: relative; overflow: hidden; transition: all 0.3s; font-weight: 500; border: none; border-radius: 8px; padding: 10px 20px; display: flex; align-items: center; gap: 8px; }
.restore-button { background: linear-gradient(45deg, #4caf50, #81c784); color: #fff; }
.delete-button { background: linear-gradient(45deg, #e53935, #ff5252); color: #fff; }
.btn-icon { font-size: 16px; }
.btn-hover:not([disabled]):hover { transform: scale(1.05); box-shadow: 0 4px 15px rgba(0,0,0,0.2); }
.btn-hover[disabled] { background: #e0e0e0; color: #9e9e9e; cursor: not-allowed; box-shadow: none; }
.btn-icon-hover { transition: all 0.3s; }
.btn-icon-hover:hover { transform: scale(1.2); }

/* 表格样式 */
:deep(.el-table) { border-radius: 12px; overflow: hidden; box-shadow: 0 2px 10px rgba(0,0,0,0.03); background: #fff; }
:deep(.el-table__header) th { font-size: 15px; font-weight: 600; background: #f5f7fa; padding: 16px 20px; border-bottom: 1px solid #e2e8f0; }
:deep(.el-table__body) td { padding: 16px 20px; font-size: 14px; border-bottom: 1px solid #f1f5f9; color: #334155; }
:deep(.el-table--enable-row-hover .el-table__body tr:hover > td) { background: #f0f7ff; }
:deep(.el-button-group .el-button) { padding: 4px 8px; }
:deep(.el-button-group .el-button + .el-button) { margin-left: 8px; }

/* 空状态样式 */
.empty-state { display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 80px 0; gap: 12px; color: #94a3b8; text-align: center; }
.empty-icon { font-size: 48px; opacity: 0.6; color: #e53935; }
.empty-text { font-size: 16px; font-weight: 500; }
.empty-desc { font-size: 14px; max-width: 300px; }

/* 动画类 */
.animate-fade-in { animation: fadeIn 0.6s ease forwards; opacity: 0; }
.animate-fade-in-up { animation: fadeInUp 0.6s ease forwards; opacity: 0; transform: translateY(20px); }
.dynamic-button:not([disabled]) { animation: pulse 2s infinite; }

/* 动画关键帧 */
@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
@keyframes fadeInUp { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }
@keyframes pulse { 0%, 100% { transform: scale(1); filter: brightness(1); } 50% { transform: scale(1.03); filter: brightness(1.1); } }

/* 响应式适配 - 平板 */
@media (max-width: 968px) {
  .recycle-view { padding: 16px; }
  .operation-bar { padding: 0 16px; margin-bottom: 16px; }
  .dynamic-button { padding: 8px 16px; font-size: 13px; }
  :deep(.el-table__header) th, :deep(.el-table__body) td { padding: 14px 16px; }
  .empty-state { padding: 60px 0; }
  .empty-icon { font-size: 40px; }
}

/* 响应式适配 - 手机 */
@media (max-width: 576px) {
  .recycle-view { padding: 12px; }
  .operation-bar { padding: 0 12px; margin-bottom: 12px; flex-direction: column; gap: 8px; }
  .dynamic-button { width: 100%; justify-content: center; padding: 10px 0; }
  :deep(.el-table__header) th { font-size: 13px; padding: 12px 8px; }
  :deep(.el-table__body) td { font-size: 12px; padding: 12px 8px; }
  :deep(.el-table-column--selection) { width: 40px !important; }
  .empty-state { padding: 40px 0; }
  .empty-icon { font-size: 32px; }
  .empty-text { font-size: 14px; }
  .empty-desc { font-size: 12px; }
  /* 隐藏次要列 */
  :deep(.el-table-column:nth-child(4)), :deep(.el-table-column:nth-child(5)) { display: none; }
}
</style>